﻿using QYmall.Core.IServices;
using QYmall.Core.IServices.Alipay;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QYmall.Core.API.Controllers
{
    /// <summary>
    /// 支付宝通知回调
    /// </summary>
    [Route("alipay/notify")]
    [ApiController]
    public class AlipayNotifyServiceController : ControllerBase
    {
        private readonly IAlipayNotifyService _alipayNotifyService;
        private readonly IOrderCollectionService _orderCollectionService;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public AlipayNotifyServiceController(IAlipayNotifyService AlipayNotifyService, IOrderCollectionService orderCollectionService)
        {
            _alipayNotifyService = AlipayNotifyService;
            _orderCollectionService = orderCollectionService;
        }

        /// <summary>
        /// APP支付成功回调
        /// 示例：/alipay/notify/transactions/app
        /// </summary>
        [HttpPost("transactions/{type}")]
        public async Task<IActionResult> Transactions([FromRoute] string type)
        {
            bool result = false;
            if (type.ToLower() == "app")
            {
                var model = await _alipayNotifyService.AppPay(Request);
                if (model != null && model.OutTradeNo != null)
                {
                    //修改订单状态
                    result = await _orderCollectionService.ConfirmAsync(model.OutTradeNo);
                }
            }
            if (type.ToLower() == "pc")
            {
                var model = await _alipayNotifyService.PagePay(Request);
                if (model != null && model.OutTradeNo != null)
                {
                    //修改订单状态
                    result = await _orderCollectionService.ConfirmAsync(model.OutTradeNo);
                }
            }
            if (type.ToLower() == "h5")
            {
                var model = await _alipayNotifyService.WapPay(Request);
                if (model != null && model.OutTradeNo != null)
                {
                    //修改订单状态
                    result = await _orderCollectionService.ConfirmAsync(model.OutTradeNo);
                }
            }
            //返回结果
            if (!result)
            {
                return BadRequest("fail");
            }
            return Ok("success");
        }

    }
}
